(function(){
	/**
	 * 触摸管理器 
	 * @author
	 * 
	 */
	var supportTouch = (window.Modernizr && Modernizr.touch === true) || (function () {
	    'use strict';
	    return !!(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch);
	})();
	var supportMsPointer = window.navigator.msPointerEnabled,
	supportPointer = window.navigator.pointerEnabled,
	TouchEvents = (function(){
		 /*=========================
	      Define Touch Events
	      ===========================*/
	    var desktopEvents = ['mousedown', 'mousemove', 'mouseup'];
	    if (supportMsPointer) desktopEvents = ['MSPointerDown', 'MSPointerMove', 'MSPointerUp'];
	    if (supportPointer) desktopEvents = ['pointerdown', 'pointermove', 'pointerup'];
	    return {
	        touchStart : supportTouch  ? 'touchstart' : desktopEvents[0],
	        touchMove : supportTouch ? 'touchmove' : desktopEvents[1],
	        touchEnd : supportTouch ? 'touchend' : desktopEvents[2]
	    };
	})();
	
	function  getTimeStamp(){
		return (new Date()).getTime();
	}
	
	/**
	 * 事件绑定 
	 */
	function bind(el, event, listener, useCapture) {
        'use strict';
        if (typeof useCapture === 'undefined') {
            useCapture = false;
        }

        if (el.addEventListener) {
            el.addEventListener(event, listener, useCapture);
        }
        else if (el.attachEvent) {
            el.attachEvent('on' + event, listener);
        }
   }
   /**
    * 解除事件绑定 
    */
   function unbind(el, event, listener, useCapture) {
        'use strict';
        if (typeof useCapture === 'undefined') {
            useCapture = false;
        }

        if (el.removeEventListener) {
            el.removeEventListener(event, listener, useCapture);
        }
        else if (el.detachEvent) {
            el.detachEvent('on' + event, listener);
        }
    }
    
    function extend(target, obj){
    	for ( var i in obj ) {
			target[i] = obj[i];
		}
		return target;
    }
	
	/**
	 *touch管理 
	 */
	function TouchesManager(options){
		this.init(options);
	}
	
	TouchesManager.prototype = {
	   	init:function(options){
	   		var defaults = {
	   			element:window.document,
	   			auto : true, //自动绑定
	   			onTouchStart:function(){}, //在触摸开始时触发
	   			onTouchMove:function(){}, //在触摸移动时触发
	   			onTouchEnd:function(){}, //在触摸结束时触发
	   			onZoomMove:function(){}, //缩放时促发
	   			onZoomEnd:function(){}, //缩放时促发
	   			threshold:100, //移动触发阀值
	   			filter:function(){return false;}
	   		};
	   		this.settings = extend(defaults, options);
		    this.bindEvent();
		},
		bindEvent:function(){
			var _this = this;
			
			var onTouchStart = function(event){
				if(_this.settings.filter(event)){
					return true;
				}
				event.preventDefault();
				if(!_this._startPointer){
					_this._startPointer = new Pointer();
				}
				_this._startPointer.push(event);
				_this.settings.onTouchStart(event, _this._startPointer.getTouches());
			};
			
			var onTouchMove = function(event){
				if(_this.settings.filter(event)){
					return true;
				}
				event.preventDefault();
				if(_this._startPointer){
					if(!_this._endPointer){
						_this._endPointer = new Pointer();
					}
					_this._endPointer.push(event);
					var startTouches = _this._startPointer.getTouches();
					var currentTouches = _this._endPointer.getTouches();
					_this.settings.onTouchMove(startTouches, currentTouches);
				}
			};
			
			
			var onTouchEnd = function(event){
				if(_this.settings.filter(event)){
					return true;
				}
				event.preventDefault();
				if(_this._startPointer && _this._endPointer){
					var startTouches = _this._startPointer.getTouches();
					var currentTouches = _this._endPointer.getTouches();
					_this.settings.onTouchEnd(startTouches, currentTouches);
				}
				_this._startPointer = null;
				_this._endPointer = null;
			};
			
			this.bindTouchEvent = function(){
				bind(_this.settings.element, TouchEvents["touchStart"], onTouchStart);
				bind(_this.settings.element, TouchEvents["touchMove"], onTouchMove);
				bind(_this.settings.element, TouchEvents["touchEnd"], onTouchEnd);
			};
			
			this.unbindTouchEvent = function(){
				unbind(_this.settings.element, TouchEvents["touchStart"], onTouchStart);
				unbind(_this.settings.element, TouchEvents["touchMove"], onTouchMove);
				unbind(_this.settings.element, TouchEvents["touchEnd"], onTouchEnd);
			};
			
			if(this.settings.auto){
				this.bindTouchEvent();
			}
		},
		getElement:function(){
			return this.settings.element;
		}
	};
	
	/**
	 * 触摸列表
	 */
	function Pointer(options){
		this.init(options);
	}
	
	Pointer.prototype = {
		init:function(options){
			this._touches = [];
		},
		push:function(e){
			if(supportTouch){
				this.clear();
				for(var i=0; i<e.touches.length; i++){
					var touchBean = new TouchBean({
						id:i,
						pageX:e.touches[i].pageX,
						pageY:e.touches[i].pageY
					});
					this._touches.push(touchBean);
				}
			}
			else{
				var pointerId = e.pointerId||0;
				var pos = this.findById(pointerId);
				var pageX = e.pageX|| e.clientX;
				var pageY = e.pageY||e.clientY;
				
				if(pos > -1){
					var touchBean = this._touches[pos];
					touchBean.update(pageX, pageY);
					this._touches[pos] = touchBean;
				}
				else{
					var touchBean = new TouchBean({
						id:pointerId,
						pageX:pageX,
						pageY:pageY
					});
					
					//兼容wp8 判断其他触摸点是否超时
					if(!this.check(touchBean.timeStamp)){
						this.clear();
					}
					
					this._touches.push(touchBean);
				}
				
			}
		},
		pop:function(e){
			if(e.pointerId){
				this.remove(e.pointerId);
			}
			else{
				this.clear();
			}
		},
		remove:function(id){
			for(var i in this._touches){
				if(this._touches[i].id == id){
					this._touches.splice(i, 1);
				}
			}
		},
		findById:function(id){
			for(var i in this._touches){
				if(this._touches[i].id == id){
					return i;
				}
			}
			return -1;
		},
		check:function(timeStamp){
			for(var i in this._touches){
				if(this._touches[i].timeStamp  != timeStamp){
					return false;
				}
			}
			return true;
		},
		clear:function(){
			this._touches = [];
		},
		length:function(){
			return this._touches.length;
		},
		getTouches:function(){
			return this._touches;
		}
	};
	
	
	/**
	 * 触摸Bean 
 	 * @param {Object} options
	 */
	function TouchBean(options){
		this.init(options);
	}
	TouchBean.prototype = {
		init:function(options){
			this.id = options.id;
			this.pageX = options.pageX;
			this.pageY = options.pageY;
			this.timeStamp = getTimeStamp();
		},
		update:function(x, y){
			this.pageX = x;
			this.pageY = y;
			this.timeStamp = getTimeStamp();
		}
	};
	
	TouchesManager.TouchEvents = TouchEvents;
	
	window.TouchesManager = TouchesManager;
	
})();
